<?php


namespace app\model;


use app\process\CalFeature;
use app\service\MqttService;
use Co\Channel;
use fast\Http;
use Ixudra\Curl\Facades\Curl;
use think\facade\Log;
use think\Model;
use Swoole\Coroutine as Co;

class MqttUserManage extends Model {



    /**
     * 注册回调省厅，并注册洞鉴
     * @param $id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function callback($id,$photo=''){

        $service_type=config('capture.platform');
        $service=null;
        eval('$service= new app\service\impl\Albums'.$service_type.'ServiceImpl();');
        $data=MqttUserManage::find($id);
        $old_photo=base64_img($data->photo,0);
        if(!$photo){
            $photo=base64_img($data->photo);
        }
        $data->photo=$photo;
        //发送洞鉴
        $post_ai_return=$service->create_face($data);
        if(!$post_ai_return){
            Log::alert('注册回调省厅、发送洞鉴失败：'.$data);

        }else{
            $post_ai_return_array=json_decode($post_ai_return,true);
            $photo_id=0;
            if($post_ai_return_array['code']===0){
                $photo_id=$post_ai_return_array['data']['photo_id'];
            }
            MqttUserManage::where('id',$id)->update(['status'=>'1','local_json'=>$post_ai_return,'photo_id'=>$photo_id]);
            if($data->callback_status==1){
                return;
            }
        }

        //回调
        $post_json=array(
            'id'=>$data->ywlsh+0,
            'statusName'=>'审核通过',
            'statusCode'=>'02',
            'communityCode'=>$data->address_id,
            'period'=>'always',
        );
        /*$post_json[]=[
            'ywlsh'=>$data->ywlsh+0,
            'result'=>'1',
            'period'=>'always',
        ];*/
        $areaname=$data['address_id'];
        $_aizone=new Aizone();
        $access_value=$_aizone->get_token($areaname);

        $posturl='https://ezc.chinapopin.com/zhxq-resource/user/userCallback';

        $login_header=array(
            CURLOPT_HTTPHEADER=>['Content-Type:application/json;charset=UTF-8','Authorization:bearer '.$access_value],
        );


        $post_ai_return = Http::post($posturl,json_encode($post_json),$login_header);
        Log::info('返回省厅header：'.json_encode($login_header));
        Log::info('返回省厅：'.json_encode($post_json));
        Log::info('返回省厅结果：'.$post_ai_return);
        sleep(1);
        $res=json_decode($post_ai_return,true);
        if(!$res){
            $access_value=$_aizone->get_token($areaname,1);
            $login_header=array(
                CURLOPT_HTTPHEADER=>['Content-Type:application/json;charset=UTF-8','Authorization:bearer '.$access_value],
            );
            $post_ai_return = Http::post($posturl,json_encode($post_json),$login_header);
            Log::info('二次返回省厅header：'.json_encode($login_header));
            Log::info('二次返回省厅：'.json_encode($post_json));
            Log::info('二次返回省厅结果：'.$post_ai_return);
            $res=json_decode($post_ai_return,true);
        }
        if($res&&$res['code']==20000){
            $status=1;
        }else{
            $status=0;
            $post_ai_return='{}';
        }
        MqttUserManage::where('id',$id)->update(['out_json'=>$post_ai_return,'callback_status'=>$status,'callback_time'=>date('Y-m-d H:i:s')]);
        //向面板机发送数据
        Log::info("向面板机发送数据");
        $_panel=new \app\model\Panel();
        $_panel->add_people($areaname,$data->id,$data['name'],$data->ywlsh,$old_photo);

    }

    public function send_hk_mqtt($id) {
        $data=MqttUserManage::find($id);
        $old_photo=base64_img($data->photo,0);

        $_panel=new \app\model\Panel();
        return $_panel->add_people($data['address_id'],$data->id,$data['name'],$data->ywlsh,$old_photo);
    }

    /*public function getFeature() {
        \Swoole\Runtime::enableCoroutine();
        //获取所有feature为空的数据
        $lists=$this->whereNull('feature')->limit(100)->field('id,photo,feature')->select();
        foreach ($lists as $list) {
            $requests[]=\Swoole\Coroutine::create(function ()use($list){
                $feature=$this->get_feature($list['path']);
                if($feature){
                    $list->feature=$feature;
                    $list->save();
                }
            });
        }
        \Swoole\Coroutine::wait($requests);
    }*/

    public function getFeature() {
        //获取所有feature为空的数据
        $lists=$this->where('feature_status',0)->limit(100)->field('id,photo,feature,feature_status')->select();
        $_calFeature=new CalFeature();
        foreach ($lists as $list) {
            $feature=$_calFeature->get_feature($list['photo']);
            if($feature){
                $list->feature=$feature;
                $list->feature_status=1;
            }else{
                $list->feature_status=2;
            }
            $list->save();
        }
    }


    public function getFeatureFail(){
        //获取所有feature为空的数据
        $lists=$this->where('feature_status',2)->limit(100)->field('id,photo,feature,feature_status')->select();
        Log::info("获取失败feature:");
        $_calFeature=new CalFeature();
        foreach ($lists as $list) {
            //$sourceImage = imagecreatefromjpeg($list['photo']);
            // 设置JPEG图像的质量（0-100），100为最高质量
            $file=str_replace(".jpg","_tmp.jpg",$list['photo']);
            // 保存图片为JPEG格式
            //imagejpeg($sourceImage,$file , $quality);

            // 释放内存
            //imagedestroy($sourceImage);
            $image = \think\Image::open($list['photo']);
            $width = $image->width();
            $height=$image->height();
            Log::info("file:".$file);
            if($width>400){
                $image->thumb(400, 400*$height/$width)->save($file);
            }else{
                $file=$list['photo'];
            }
            $file_jpeg=str_replace(".jpg",".jpeg",$file);
            $sourceImage = imagecreatefromjpeg($file);
            // 保存图片为JPEG格式
            imagejpeg($sourceImage, $file_jpeg, 100);

            // 释放内存
            imagedestroy($sourceImage);

            $feature=$_calFeature->get_feature($file_jpeg);
            if($feature){
                $list->feature=$feature;
                $list->feature_status=1;
            }else{
                $list->feature_status=3;
            }
            $list->save();
            unlink($file);
        }
    }

    public function send_mqtt_user_manage($id=0) {
        $where[]=['mqtt_status','=',0];
        //$where[]=['address_id','=','511099410000-003'];
        if($id){
            $where[]=['id','=',$id];
        }
        $lists=$this->where($where)->limit(10)->field('id,address_id,name,photo,mqtt_status')->order("id desc")->select();
        if($lists){
            $mqttService = new MqttService();
            $msg=array(
                'client_id'=>"REGISTER_FACE",
                'version'=>'0.2',
                'cmd'=>'create_face',
                'idcardNum'=>'0',
                'idcardper'=>'0',
                'per_type'=>0,
                'usr_type'=>0,
                's_time'=>0,
                'e_time'=>4077927429
            );
            $_aizone=new Aizone();
            $_device=new ViidDevice();
            //var_dump($lists);
            foreach ($lists as $list){
                $msg['cmd_id']=$list['id'];
                $msg['per_id']=$list['id']."";
                $msg['per_name']=$list['name'];
                $photos=explode("user-capture-photos",$list['photo']);
                $msg['img_url']="http://220.166.79.246:8099".$photos[1];
                $aizone=$_aizone->where('name_code',$list['address_id'])->find();
                if($aizone){
                    $devices=$_device->where('aizone_id',$aizone['id'])->where('dev_type',1)->where('panel_type',99)->column('ape_id');
                    //var_dump($devices);
                    if($devices){
                        foreach ($devices as $sn) {
                            $topic='face/'.$sn.'/request';
                            //$mqttService->subscribe($topic,null);
                            $mqttService->publish($topic, json_encode($msg),2);
                            sleep(1);
                        }
                        $this->where('id',$list['id'])->save(['mqtt_status'=>1]);
                    }else{
                        $this->where('id',$list['id'])->save(['mqtt_status'=>2]);
                    }

                }

            }
        }

    }

    public function edit_pic($id,$file) {
        $info=$this->find($id);
        $filePath=config('capture.apply_path').date('Ym').'/'.date('d').'/';
        $file->move($filePath,$id.'.jpg');
        $info->photo=$filePath.$id.'.jpg';
        $info->save();
    }

}